package conf

/*******************************************************************************
Copyright:cloud
Author:cloudapex@126.com
Version:1.0
Date:2020-06-12
Description: 企业微信配置文件
*******************************************************************************/
import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"sync"
	"time"

	"gitee.com/cloudapex/ulern/cto"
	"gitee.com/cloudapex/ulern/htp"
	"gitee.com/cloudapex/ulern/util"
)

type ParamSetting struct {
	CorpId     string `json:"corpid"`
	CorpSecret string `json:"corpsecret"`
	Url        string `json:"url"`
}
type AccessToken struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int64  `json:"expires_in"` //秒 默认返回是2小时
	ExpireAt    int64  `json:"expireAt"`   //在什么时候过期
	ErrCode     int    `json:"errcode" id:"-1"`
	ErrMsg      string `json:"errmsg"`
}

//------------------------------------------------------------------------------
//======================================DB======================================
//------------------------------------------------------------------------------
var Wechat *wechatConf

func init() { Wechat = cto.Preload("MT_Wechat", &wechatConf{}).(*wechatConf) }

type wechatConf struct {
	mutx sync.Mutex
	main *mainWechat

	wxToken AccessToken // 缓存的有效token
}
type mainWechat struct {
	Param ParamSetting `json:"param"`
}

func (this *wechatConf) HandleInit() error {
	this.main = &mainWechat{}
	data, err := ioutil.ReadFile(this.HandlePath())
	if err != nil {
		return err
	}
	if err := json.Unmarshal(data, this.main); err != nil {
		return err
	}
	if err := this.reqAccessToken(); err != nil {
		return err
	}
	return nil
}
func (this *wechatConf) HandlePath() string { return util.ExePathJoin("confs/wx_secret.json") }

func (this *wechatConf) HandleContent() string {
	b, err := json.MarshalIndent(this.main, "", "\t")
	if err != nil {
		return err.Error()
	}
	return string(b)
}
func (this *wechatConf) HandleReload() error {
	data, err := ioutil.ReadFile(this.HandlePath())
	if err != nil {
		return err
	}

	temp := &mainWechat{}
	if err := json.Unmarshal(data, temp); err != nil {
		return err
	}
	defer util.UnLock(util.Lock(&this.mutx))
	// update some fields
	return cto.ErrSettingNotNeed
}

//------------------------------------------------------------------------------
//================================开放方法=======================================
//------------------------------------------------------------------------------
func (this *wechatConf) Stg() *mainWechat {
	defer util.UnLock(util.Lock(&this.mutx))
	return this.main
}
func (this *wechatConf) reqAccessToken() error {
	// 获取微信token
	url := this.main.Param.Url + "corpid=" + this.main.Param.CorpId + "&corpsecret=" + this.main.Param.CorpSecret
	rsp, err := htp.HttpRequest("GET", url, "", nil)
	if err != nil {
		return err
	}
	if err := json.Unmarshal(rsp.Body, &this.wxToken); err != nil {
		return err
	}

	if this.wxToken.ErrCode != 0 {
		return fmt.Errorf("获取wxToken失败:%s", this.wxToken.ErrMsg)
	}
	this.wxToken.ExpireAt = time.Now().Unix() + this.wxToken.ExpiresIn - 60
	return nil
}

func (this *wechatConf) Param() ParamSetting { return this.Stg().Param }

func (this *wechatConf) GetAccessToken() (string, error) {

	if this.wxToken.ExpireAt < time.Now().Unix() {
		return this.wxToken.AccessToken, nil
	}

	if err := this.reqAccessToken(); err != nil {
		return "", err
	}

	return this.wxToken.AccessToken, nil
}

//------------------------------------------------------------------------------
